package com.example.administrator.androidros.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.base.BaseActivity;
import com.example.administrator.androidros.base.BaseFragment;
import com.example.administrator.androidros.event.MessageEvent;
import com.example.administrator.androidros.fragment.HomePageFragment;
import com.example.administrator.androidros.fragment.MessageFragment;
import com.example.administrator.androidros.fragment.MyFragment;
import com.example.administrator.androidros.model.MessageModel;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.ServerConstants;
import com.hhc.netty.NettyClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity {
    @BindView(R.id.activity_main_fragment_container)
    protected FrameLayout activity_main_fragment_container;

    @BindView(R.id.activity_main_bottom_navigation_bar)
    protected BottomNavigationBar activity_main_bottom_navigation_bar;

    private TextBadgeItem messageBadgeItem;
    private BottomNavigationItem bottomNavigationItem;
    private List<BaseFragment> fragmentList;
    private boolean isExit = false;//退出状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initData() {
        fragmentList = getFragments();
        initBottomNavigationBar();
        replaceFragment(0);
        initNetty();
    }

    @Override
    protected void onFailure(int requestCode, Object object) {

    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
                case 1002:
                    MessageModel[] deviceModels = (MessageModel[]) HttpUtils.getData(object, MessageModel[].class);
                    EventBus.getDefault().post(new MessageEvent(deviceModels.length));
                    break;
                default:
                    break;
            }
        }
    }

    public void initBottomNavigationBar() {
        activity_main_bottom_navigation_bar.setMode(BottomNavigationBar.MODE_DEFAULT);
        activity_main_bottom_navigation_bar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_DEFAULT);
        activity_main_bottom_navigation_bar.setBarBackgroundColor(R.color.common_head);
        activity_main_bottom_navigation_bar.setActiveColor(R.color.common_bt_bg_2_80);
        activity_main_bottom_navigation_bar.setInActiveColor(R.color.white);
        messageBadgeItem = new TextBadgeItem();
        bottomNavigationItem = new BottomNavigationItem(R.mipmap.icon_message, getString(R.string.main_bottom_navigation_item2)).setActiveColorResource(R.color.common_bt_bg_2_80).setBadgeItem(messageBadgeItem);
        activity_main_bottom_navigation_bar
                .addItem(new BottomNavigationItem(R.mipmap.icon_homepage, getString(R.string.main_bottom_navigation_item1)).setActiveColorResource(R.color.common_bt_bg_2_80))
                .addItem(bottomNavigationItem)
//                .addItem(new BottomNavigationItem(R.mipmap.icon_families, getString(R.string.main_bottom_navigation_item3)).setActiveColorResource(R.color.common_head_blue2))
                .addItem(new BottomNavigationItem(R.mipmap.icon_my, getString(R.string.main_bottom_navigation_item4)).setActiveColorResource(R.color.common_bt_bg_2_80))
                .setFirstSelectedPosition(0)
                .initialise();
        activity_main_bottom_navigation_bar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                replaceFragment(position);
            }

            @Override
            public void onTabUnselected(int position) {
                if (fragmentList != null) {
                    if (position < fragmentList.size()) {
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        Fragment fragment = fragmentList.get(position);
                        ft.remove(fragment);
                        ft.commitAllowingStateLoss();
                    }
                }
            }

            @Override
            public void onTabReselected(int position) {

            }
        });
        getMessageList();
    }

    private List<BaseFragment> getFragments() {
        List<BaseFragment> fragments = new ArrayList<>();
        fragments.add(HomePageFragment.newInstance());
        fragments.add(MessageFragment.newInstance());
//        fragments.add(TaskFragment.newInstance());
//        fragments.add(NotificationFragment.newInstance());
        fragments.add(MyFragment.newInstance());
        return fragments;
    }

    private void setDefaultFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        HomePageFragment homePageFragment = new HomePageFragment();
        transaction.replace(R.id.activity_main_fragment_container, homePageFragment);
        transaction.commit();
    }

    private void replaceFragment(int position) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = fragmentList.get(position);
        if (fragment.isAdded()) {
            transaction.replace(R.id.activity_main_fragment_container, fragment);
        } else {
            transaction.add(R.id.activity_main_fragment_container, fragment);
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                if (NettyClient.getInstance().getConnectState() == NettyClient.CONNECTED) {
                    NettyClient.getInstance().disconnect();
                }
                exit();
            } else {
                Toast.makeText(MainActivity.this, getResources().getString(R.string.common_press_quit), Toast.LENGTH_SHORT).show();
                isExit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void initNetty() {
        NettyClient.getInstance().doConnect();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent messageEvent) {
        messageBadgeItem.setText(String.valueOf(messageEvent.getNumber()));
    }

    protected void getMessageList() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("messageType", "20");
        jsonObject.put("messageRead", "0");
        jsonObject.put("messageStatus", "0");
        HttpUtils.post(mBaseActivity, 1002, ServerConstants.QUERY_MESSAGE, jsonObject.toString(), this);//主要回调的类
    }
}
